import cx from 'classnames';
import React from 'react';
import TableHeader from './TableHeader';

import { getColumnPinningStyle } from '../../utils';

import type { Table } from '@tanstack/react-table';
import type {
  AnyObject,
  ColumnMeta,
  ColumnPinning,
  ColumnPinningInfo,
  DragType,
  Size,
} from '../../type';

export interface Props<T extends AnyObject, Context = any> {
  prefixCls: string;
  size?: Size;
  table: Table<T>;
  dragTypes: DragType[];
  columnPinning: ColumnPinning;
  columnPinningInfo: ColumnPinningInfo;
  bordered?: boolean;
  isShowBoxShadow?: boolean;
  isCanResizeColumn?: boolean;
  context: React.Context<Context>;
}

function TableThead<T extends AnyObject>(props: Props<T>) {
  const {
    prefixCls,
    table,
    size,
    dragTypes,
    columnPinning,
    columnPinningInfo,
    bordered,
    isShowBoxShadow,
    isCanResizeColumn,
    context,
  } = props;

  return (
    <div className={cx(`${prefixCls}-section`, `${prefixCls}-thead`)}>
      {table.getHeaderGroups().map((headerGroup) => (
        <div role="row" className={cx(`${prefixCls}-tr`)} key={headerGroup.id}>
          <div role="row" className={`${prefixCls}-tr-box`}>
            {headerGroup.headers.map((header) => {
              const style = getColumnPinningStyle(
                header.id,
                columnPinningInfo,
                columnPinning,
                isShowBoxShadow,
              );
              const { column } = header;
              const { columnDef } = column;
              const columnMeta = (columnDef.meta as ColumnMeta<T>) || {};
              const { align, className } = columnMeta;

              const props = {
                isCanResizeColumn,
                bordered,
                prefixCls,
                align,
                className,
                header,
                table,
                style,
                size,
                context,
              };
              return (
                <TableHeader
                  key={header.id}
                  isCanDrag={dragTypes.includes('column')}
                  {...props}
                />
              );
            })}
          </div>
        </div>
      ))}
    </div>
  );
}

export default TableThead;
